class K3d < Formula
  desc "Little helper to run Rancher Lab's k3s in Docker"
  homepage "https://k3d.io"
  url "https://github.com/rancher/k3d/archive/v4.1.0.tar.gz"
  sha256 "5a432d4a9a7a7ea517d7370249940cb0be590a7e65d998fc4eae43d628996321"
  license "MIT"

  livecheck do
    url :stable
    regex(/^v?(\d+(?:\.\d+)+)$/i)
  end

  bottle do
    sha256 cellar: :any_skip_relocation, arm64_big_sur: "2bb96695d0cba75d48724516817de2a79d90c153d27cdb8b271b5af22351883e"
    sha256 cellar: :any_skip_relocation, big_sur:       "a6649d74709885fa91c80d2ee81062e85380809d315db772efb204cf2014516e"
    sha256 cellar: :any_skip_relocation, catalina:      "5746900c6685ebb09e68b245994a75755f8ec0602e136fbe762f52cd6b6e0b16"
    sha256 cellar: :any_skip_relocation, mojave:        "5e9f2fff1d7665c156a1cbc37b5e68fbf75b40cf3f7abf11e71c5d29329484d2"
    sha256 cellar: :any_skip_relocation, x86_64_linux:  "82e796dc5e5b18f50a7a49adacf975b6829ba5d80af1d930fd96e793bc25d273"
  end

  depends_on "go" => :build

  def install
    system "go", "build",
           "-mod", "vendor",
           "-ldflags", "-s -w -X github.com/rancher/k3d/v#{version.major}/version.Version=v#{version}"\
           " -X github.com/rancher/k3d/v#{version.major}/version.K3sVersion=latest",
           "-trimpath", "-o", bin/"k3d"

    # Install bash completion
    output = Utils.safe_popen_read("#{bin}/k3d", "completion", "bash")
    (bash_completion/"k3d").write output

    # Install zsh completion
    output = Utils.safe_popen_read("#{bin}/k3d", "completion", "zsh")
    (zsh_completion/"_k3d").write output
  end

  test do
    assert_match "k3d version v#{version}\nk3s version latest (default)", shell_output("#{bin}/k3d --version")
    # Either docker is not present or it is, where the command will fail in the first case.
    # In any case I wouldn't expect a cluster with name 6d6de430dbd8080d690758a4b5d57c86 to be present
    # (which is the md5sum of 'homebrew-failing-test')
    output = shell_output("#{bin}/k3d cluster get 6d6de430dbd8080d690758a4b5d57c86 2>&1", 1).split("\n").pop
    assert_match "No nodes found for given cluster", output
  end
end
